<template>
  <div>
    <div id="map" class="map" tabindex="0"></div>
    <TyphoonInfo
      ref="typhoonInfo"
      :typhoonData="this.typhoonData"
    ></TyphoonInfo>
  </div>
</template>

<script>
import 'ol/ol.css'
import Map from 'ol/Map'
import OSM from 'ol/source/OSM'
import TileLayer from 'ol/layer/Tile'
import View from 'ol/View'
import { getTyphoonData } from '../../data/api'
// 这个是什么
import Feature from 'ol/Feature'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
// 球面数据转换为 平面图形
import { Point, MultiLineString, LineString, Polygon } from 'ol/geom'
import { fromLonLat } from 'ol/proj'
import { Fill, Circle, Style } from 'ol/style'
// import { parse } from 'path-to-regexp'
import featureObj from '../../common/js/feature'
import TyphoonInfo from './TyphoonInfo.vue'

export default {
  components: { TyphoonInfo },
  data() {
    return {
      tfOverlay: null,
      typhoonData: {},
      map: null,
      lastShowSolar: null
    }
  },
  methods: {
    // overlay 添加叠加层
    addOverlay: function() {
      const overlay = new Overlay({
        element: this.$typhoonInfo.$el,
        autoPan: true,
        autoPanAnimation: {
          duration: 250
        }
      })
      overlay.setPositon(undefined)
      this.tfOverlay = overlay
      this.map.addOverlay(overlay)
    },
    // 设置弹窗位置
    setTFINFOPosition: function(points) {
      let position = fromLonLat([points.lng, points.lat])
      this.tfOverlay.setPositon(position)
    },
    // 获取数据
    darwTyphoonPath: async function() {
      const { data } = await getTyphoonData()
      // console.log(data, 'datadata')
      let points = data[0].points
      // console.log(points, "points");
      let features = []
      // 两点之间的连线
      let positions = []
      // 添加圆点
      for (let i = 0; i < points.length; i++) {
        let position = [points[i].lng, points[i].lat]
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position))
        })
        // 设置图像的圆点的颜色
        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: this.judgeColorByWindLevel(points[i].strong)
              }),
              radius: 4
            })
          })
        )

        // 添加两条线之间的连接点
        if (i != points.length - 1) {
          let nextPosition = [points[i + 1].lng, points[i + 1].lat]
          positions.push([fromLonLat(position), fromLonLat(nextPosition)])
        }
        features.push(featurePoint)
      }
      // 线条的绘制
      let featureLine = new Feature({
        geometry: new MultiLineString(positions)
      })
      features.push(featureLine)
      // console.log(features, 'xiantiao')
      // 适量图层
      let layer = new VectorLayer()
      // 适量数据源
      let source = new VectorSource()
      // 有错误
      source.addFeatures(features)
      layer.setSource(source)
      // this.map.addLayer(layer)
    },
    // 设置一个定时器 来控制 台风的进行速度
    darwTyphoonPathInterval: async function() {
      const { data } = await getTyphoonData()
      // console.log(data)
      let points = data[0].points
      // console.log(points.length, 'length')
      let index = 0
      let layer = new VectorLayer()
      let source = new VectorSource()
      layer.setSource(source)
      // console.log('points.length', points.length)

      let intervalLogo = setInterval(() => {
        if (index == points.length) {
          clearInterval(intervalLogo)
          return
        }

        let position = [points[index].lng, points[index].lat]
        // 点的数据源
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position))
        })
        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: this.judgeColorByWindLevel(points[index].strong)
              }),
              radius: 4
            })
          })
        )
        // hover 触发事件
        // hover事件
        featurePoint.set('typhoonPoint', true)
        // 调用风圈
        if (
          points[index].radius7.length != 0 ||
          points[index].radius7 != null
        ) {
          let featureSolar = this.drawSolar(points[index])
          // 定义一个新的变量
          let lastShowSolar = this.lastShowSolar
          if (lastShowSolar != null) {
            source.removeFeature(lastShowSolar)
          }
          // console.log(featureSolar)
          this.lastShowSolar = featureSolar
          source.addFeature(featureSolar)
        }
        source.addFeature(featurePoint)
        if (index > 0) {
          // console.log('index+11', index)
          let lastPosition = [points[index - 1].lng, points[index - 1].lat]
          let featureLine = new Feature({
            geometry: new LineString([
              fromLonLat(position),
              fromLonLat(lastPosition)
            ])
          })
          source.addFeature(featureLine)
        }
        // 需要一个出口
        index++
      }, 100)
      this.map.addLayer(layer)
    },
    //绘制一个风圈
    drawSolar: function(points) {
      let radiusArr = points.radius7.split('|').map(item => {
        return parseFloat(item)
      })
      var Configs = {
        CIRCLE_CENTER_X: parseFloat(points.lng),
        CIRCLE_CENTER_Y: parseFloat(points.lat),
        CIRCLE_R: {
          SE: radiusArr[0] / 100,
          NE: radiusArr[1] / 100,
          NW: radiusArr[2] / 100,
          SW: radiusArr[3] / 100
        }
      }
      let positions = []
      var _interval = 6
      for (var i = 0; i < 360 / _interval; i++) {
        var _r = 0
        var _ang = i * _interval
        if (_ang > 0 && _ang <= 90) {
          _r = Configs.CIRCLE_R.NE
        } else if (_ang > 90 && _ang <= 180) {
          _r = Configs.CIRCLE_R.NW
        } else if (_ang > 180 && _ang <= 270) {
          _r = Configs.CIRCLE_R.SW
        } else {
          _r = Configs.CIRCLE_R.SE
        }
        var x = Configs.CIRCLE_CENTER_X + _r * Math.cos((_ang * 3.14) / 180)
        var y = Configs.CIRCLE_CENTER_Y + _r * Math.sin((_ang * 3.14) / 180)
        positions.push(fromLonLat([x, y]))
      }
      let feature = new Feature({
        geometry: new Polygon([positions])
      })
      feature.set('typhoonSolar', true)
      return feature
    },
    // hover事件 注册一个hover事件
    designHoverOnMap: function() {
      let _this = this //这个是为了this指向当前对象
      this.map.on('pointermove', function(ev) {
        let pixel = ev.pixel
        let feature = _this.map.forEachFeatureAtPixel(pixel, function(feature) {
          return feature
        })
        if (feature) {
          let execName = featureObj.typeJudge(feature) + 'Hover'
          featureObj[execName].apply(_this, [feature])
          console.log(featureObj, 'llllfeatureObj')
          // if (feature.get('typhoonPoint')) {
          //   _this.map.getTargetElement().style.cursor = 'pointer'
          //   _this.clearPointZoomStyle()
          //   // 改变circle的大小
          //   feature
          //     .getStyle()
          //     .getImage()
          //     .setRadius(8)
          //   feature.changed()
          //   _this.lastZoomPoint = feature
          // }
        } else {
          _this.clearPointZoomStyle()
          _this.map.getTargetElement().style.cursor = ''
        }
      })
    },
    // 根据台风登记判断坐标点颜色
    judgeColorByWindLevel: function(windlevel) {
      let map = {
        热带低压: 'red',
        热带风暴: 'blue',
        强热带风暴: 'green',
        台风: 'orange',
        强台风: 'yellow',
        超强台风: 'salmon'
      }
      return map[windlevel]
    },
    // 什么也不做
    designClickOnMap: function() {
      let _this = this
      this.map.on('click', function(element) {
        let pixel = element.pixel
        let feature = _this.map.forEachFeatureAtPixel(pixel, function(feature) {
          return feature
        })
        if (feature) {
          let execName = featureObj.typeJudge(feature) + 'Click'
          featureObj[execName].apply(_this, [feature])
          console.log(featureObj, 'click11110000')
        } else {
          console.log('no  feature')
        }
      })
    },
    test: function(execName) {
      let map = {
        typhoonPointClick: function(feature) {
          // 什么也没有做
        }
      }
      return map[execName]
    },
    // clearPoint zoom style
    clearPointZoomStyle: function() {
      let _this = this
      if (_this.lastZoomPoint != null) {
        _this.lastZoomPoint
          .getStyle()
          .getImage()
          .setRadius(4)
        _this.lastZoomPoint.changed()
      }
    }
  },
  created() {},
  mounted() {
    this.map = new Map({
      layers: [
        new TileLayer({
          source: new OSM()
        })
      ],

      target: 'map',
      view: new View({
        center: [0, 0],
        zoom: 2
      })
    })
    // this.darwTyphoonPath()
    this.darwTyphoonPathInterval()
    // hover事件
    this.designHoverOnMap()
    // click事件
    this.designClickOnMap()
  }
}
</script>

<style scoped>
.map {
  width: 100%;
  height: 100vh;
  display: fixed;
}
#map:focus {
  outline: #4a74a8 solid 0.15em;
}
</style>
